import axios from 'axios';
import { getToken, removeToken } from '@/utils/token.js';
import router from '@/router';

const request = axios.create({
  baseURL: 'http://localhost:8088/',
  timeout: 5000
})

request.interceptors.request.use(
  config => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 直接返回data，避免前端需要两次data
    return response.data;
  },
  error => {
    if (error.response?.status === 401) {
      // 移除token
      removeToken();
      // 跳转登录页
      router.navigate('/login')
      // 刷新页面
      window.location.reload()
    }
    return Promise.reject(error);
  }
);

export { request }